<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use Mail;
use Crypt;

class ForgetController extends Controller
{
    //忘记密码
    public function forget()
    {
    	return view('admin.forget.inputEmail');
    }
    // 发送邮件
    public function sendEmail(Request $request)
    {
    	// dd($request -> all());
    	$data = $request -> except('_token');
    	$res = DB::table('users') -> where('email',$data['email']) -> first();
    	if(!$res)
    	{
    		return back() ->with(['info' => '你输入的邮箱不存在']);
    	}
        	// Mail::raw('你好，这里是找回中心。您的验证码是888888',function($message){
        	// 	$message -> subject('这是一封邮件');
        	// 	$message -> to('810387871@qq.com');

    $str = ltrim(strchr($data['email'],'@'),'@');
    $host = 'mail.'.$str;
    
        $r = Mail::send('emails.estyle', ['res' => $res], function ($m) use($data){
            $m -> subject('这是一封邮件');
            $m -> to($data['email']);
    	});
        
        return view('admin.forget.success',['host' => $host]);
    }
    // 验证TOKEN值reset方法
    public function reset($id,$remember_token)
    {
        // 验证
        $data = DB::table("users") -> where('id',$id) -> first();
        // 判断
        if($data -> remember_token != $remember_token)
        {
            return redirect('/admin/forget/info') -> with(['info' => '不是一个合法的来源']);
        }else
        {
            return view('admin.forget.newpass',['id' => $id]);
        }
    }
    // 找回密码下修改密码repass
    public function repass(Request $request)
    {
        // dd($request -> all());
        $data = $request -> except('_token','id','repassword');
        if($data['password'] == $request -> repassword)
        {
            $data['password'] = Crypt::encrypt($data['password']);
            $res = DB::table("users") -> where('id',$request -> id) -> update($data);
            if($res)
            {
                return redirect('admin/login') -> with(['info' => '修改成功，请登录']);
            }
        }else
        {
            return back() -> with(['info' => '重复密码与新密码不一致']);
        }
        // return view('admin.forget.newpass');
    }
    public function info()
    {
        return view('admin.forget.info');
    }
}
